<template>
  <el-row>
    <el-col :span="3" style="margin-bottom: 8px">
      <p class="pinformation">搜索条件</p>
    </el-col>
  </el-row>
  <el-form
    :model="queryParams"
    label-width="120px"
    ref="groupJcxmGroupRef"
    @submit.native.prevent
  >
    <el-row>
      <el-col :span="13">
        <el-form-item label="检测项目组别：" prop="groupName">
          <el-input
            clearable
            v-model.trim="queryParams.groupName"
            maxlength="100"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="检测方法：" prop="methodName">
          <el-input
            clearable
            v-model.trim="queryParams.methodName"
            maxlength="100"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label-width="20px">
          <el-button type="success" @click="handleQuery()">搜索</el-button>
          <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <el-row>
    <el-col :span="3" style="margin-bottom: 8px">
      <p class="pinformation">检测项目列表</p>
    </el-col>
  </el-row>
  <el-table
    id="jcxmGroupTable"
    :data="jcxmGroupList"
    height="520px"
    class="business"
    ref="jcxmGroupRef"
    v-loading="loading"
    border
    :highlight-current-row="highLightRow"
    @row-click="rowClick"
    row-key="mJId"
    :header-cell-class-name="cellClass"
    @select="handleSelectionChange"
  >
    <el-table-column
      type="selection"
      width="55"
      align="center"
      :selectable="selectable"
    />
    <el-table-column label="检测项目组别" align="left" width="150">
      <template #default="scope">
        <dict-tag
          :id="scope.row.mJId"
          :options="lims_jcxm_group"
          :value="scope.row.mJId"
          style="display: inline"
        />
      </template>
    </el-table-column>
    <el-table-column label="检测项目" align="center" prop="jcxmName" width="200">
      <template #default="scope">
        <span v-html="transformation(scope.row.jcxmName)"></span>
      </template>
    </el-table-column>
    <el-table-column label="是否求和" align="center" width="130">
      <template #default="scope">
        <el-select
          v-if="!scope.row.jcxmId"
          v-model="scope.row.isSum"
          placeholder="请选择"
          style="width: 100%"
          @change="autoSelected(scope.row)"
        >
          <el-option
            v-for="item in isSumData"
            :label="item.label"
            :key="item.value"
            :value="item.value"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="检测方法编号" align="center" prop="methodCode" width="200" />
    <el-table-column label="检测方法名称" align="center">
      <template #default="scope">
        <span v-html="transformation(scope.row.methodName)"></span>
      </template>
    </el-table-column>
  </el-table>
  <el-row>
    <el-col :span="12">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-col>
  </el-row>
</template>

<script setup>
import { listJcxmGroup } from "@/api/store/package";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const jcxmGroupList = ref([]); // 右侧检测项目列表搜索结果
const highLightRow = ref(true); // 表格选中高亮样式
const loading = ref(false);
const { lims_jcxm_group } = proxy.useShareDict("lims_jcxm_group");
const total = ref(0);
const props = defineProps({
  params: {
    type: Object,
  },
});
const isSumData = [
  {
    value: 0,
    label: "否",
  },
  {
    value: 1,
    label: "是",
  },
];
const data = reactive({
  jcxmForm: {
    isPackage: 0,
    isMethod: "0",
    isSum: "0",
  },
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页显示条数
  },
});
const selecedMJIds = ref([]);
defineExpose({
  getList,
});
const { queryParams } = toRefs(data);
queryParams.value.packageId = props.params.packageId;
emits("handleQuerySelectedJcxmList", function (data) {
  selecedMJIds.value = data;
  handleQuery(true);
});
// 获取检测项目列表数据
function handleQuery(first) {
  queryParams.value.pageNum = 1;
  getList(first);
}

function getList(first) {
  if (!first) {
    emits("getMJIds", function (data) {
      selecedMJIds.value = data;
    });
  }
  loading.value = true;
  listJcxmGroup(queryParams.value).then((res) => {
    jcxmGroupList.value = res.rows;
    loading.value = false;
    total.value = res.total;
    // 是否默认勾选通过id判断
    nextTick(() => {
      if (selecedMJIds.value && selecedMJIds.value.length > 0) {
        jcxmGroupList.value.forEach((row) => {
          for (const item1 of selecedMJIds.value) {
            if (item1.mJId == row.mJId) {
              let children = row.children;
              //如果上述if条件成立则子节点会自动选中所以不需要再次判断是否需要选中。
              let i = 0;
              children.forEach((row1, index) => {
                if (item1.children.some((item) => item.mJId == row1.mJId)) {
                  nextTick(() => {
                    proxy.$refs["jcxmGroupRef"].toggleRowSelection(row1);
                  });
                  i++;
                }
              });
              if (i == children.length) {
                proxy.$refs["jcxmGroupRef"].toggleRowSelection(row);
              }
              if (i > 0) {
                proxy.$refs["jcxmGroupRef"].toggleRowExpansion(row);
              }
              row.isSum = item1.isSum;
              break;
            }
          }
        });
      }
    });
  });
}
function resetQuery() {
  proxy.resetForm("groupJcxmGroupRef");
  handleQuery();
}

function handleSelectionChange(selection, row) {
  const index = selection.indexOf(row);
  if (index != -1) {
    if (selecedMJIds.value.some((item) => item.mJId == row.mJId)) {
      proxy.$modal.msgError("当前检测项目已经选择！");
      nextTick(() => {
        proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
      });
      return;
    }
    //选中
    //判断选中的检测项目的方法与已选择的组内的其它项目的方法是否相同。
    if (row.children) {
      //当前检测项目组全选
      for (const jcxm of row.children) {
        if (jcxm.methodId != row.children[0].methodId) {
          proxy.$modal.msgError("当前检测项目组内的检测方法必须相同！");
          nextTick(() => {
            proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
          });
          return;
        }
      }
    } else {
      const groupId = row.groupId;
      const currentGroupJcxmList = selection.filter((item) => {
        return item.groupId == groupId;
      });
      if (currentGroupJcxmList.length > 0) {
        for (const jcxm of currentGroupJcxmList) {
          if (jcxm.methodId != row.methodId) {
            proxy.$modal.msgError("当前检测项目组内的检测方法必须相同！");
            nextTick(() => {
              proxy.$refs["jcxmGroupRef"].toggleRowSelection(row, false);
            });
            return;
          }
        }
      }
    }
  }
  if (!row.children) {
    let data = { mJId: row.groupId, jcxmName: row.groupName, children: [row] };
    emits("handleJcxm", { row: data, index: index });
    return;
  }
  emits("handleJcxm", { row: row, index: index });
}
function reselection() {
  handleQuery();
}

function rowClick() {
  highLightRow.value = true;
}
function transformation(row) {
  if (row) {
    const a = proxy.getSupAndSub(row);
    return a;
  }
}

function cellClass(row) {
  if (row.columnIndex === 0) {
    return "DisableSelection";
  }
}
function autoSelected(row) {
  const selection = proxy.$refs["jcxmGroupRef"].getSelectionRows();
  nextTick(() => {
    selection.forEach((item) => {
      proxy.$refs["jcxmGroupRef"].toggleRowSelection(item, true);
    });
  });
  emits("handleUpdateIsSum", row);
  row.children.forEach((item1) => {
    item1.isSum = row.isSum;
  });

  // jcxmGroupList.value.find(item => {
  //   if (item.mJId && item.mJId == row.mJId) {
  //     if (item.children) {
  //       if (row.isSum == 1) {
  //         const selectedMJIds = selection.map(m => {
  //           return m.mJId;
  //         })
  //         if (selectedMJIds.length > 0) {
  //           let methodId;
  //           for (const i in item.children) {
  //             const item1 = item.children[i];
  //             if (selectedMJIds.indexOf(item1.mJId) == -1) {
  //               continue;
  //             }
  //             if (!methodId) {
  //               methodId = item1.methodId;
  //             } else if (methodId != item1.methodId) {
  //               proxy.$modal.msgError("求和时当前检测项目组内的检测方法必须相同！");
  //               row.isSum = 0;
  //               return true;
  //             }
  //           }
  //         }
  //       }
  //       handleUpdateIsSum(row.mJId, row.isSum);
  //       item.children.forEach(item1 => {
  //         item1.isSum = row.isSum;
  //       })
  //     }
  //     return true;
  //   }
  // })
}
function selectable(row) {
  return true;
  // if (row.groupId || row.children) {
  //   return true;
  // } else {
  //   return false;
  // }
}
const emits = defineEmits([
  "handleJcxm",
  "handleUpdateIsSum",
  "handleQuerySelectedJcxmList",
  "getMJIds",
]);
</script>

<style>
.el-table__header .DisableSelection .cell {
  visibility: hidden;
}
</style>
